const express = require('express');
const router = express.Router();
const fs = require('fs')
const path = require('path')

const path1 = "/Users/huo/Desktop/工作/vue/SZBD/Code"
// const path1 = "/Users/huo/Desktop/工作/vue/模版/vue-admin"
// 需要过滤的文件
const filterPath = [
  "node_modules",
  ".DS_Store",
  "dist",
  "dist-ssr",
  ".local",
  ".git",
  "package-lock.json",
  "yarn.lock",
  '.gitattributes',
  ".gitignore"
  ]
// /Users/huo/Desktop/工作/vue/SZBD/Code
const getDir = (p, label,list) => {
  const p2=path.join(p,label)
  const stat = fs.lstatSync(p2);

  if (filterPath.indexOf(label) != -1) {
    return
  }
  const obj = { label}
  list.push(obj)
  // 如果是文件
  if (stat.isFile()) {
      return list
  } else {
    //@ts-ignore
    obj.children=[]
    const list = fs.readdirSync(p2)
    if (list.length > 0) {
      list.forEach(item => {
        //@ts-ignore
        getDir(p2,item,obj.children)
      })
    }
  }
}
// 获取目录
router.get('/dir', (req, res) => {
  const list = []
  getDir(path1,'code',list)
  res.json(list)
})
//获取具体文件
router.post('/content', (req, res) => {
  console.log(req.body)
  let str = `123`
  const list=req.body.path??[]
  if (list.length > 0) {
    str = path.join(path1, ...list)
    fs.exists(str, (exists) => {
      if (exists) {
        console.log("文件存在")
        try {
          const data = fs.readFileSync(str, 'utf8');
          res.json({filename: str,code: data});
        } catch (error) {
          res.json("文件读取失败")
        }
        
        // return
      } else {
        res.json("文件不存在")
      }
    })
  }
  
})
// 设置文件内容 setvalue
router.post('/setvalue', (req, res) => {
  const list=req.body.filename??[]
    fs.exists(list, (exists) => {
      if (exists) {
        console.log("文件存在")
        try {
          fs.writeFile(list,req.body.code,function(err: any){
            if(err){
              res.json("文件写入失败")
            }
            res.json("文件写入成功")
          })
        } catch (error) {
          res.json("文件写入失败")
        }
      } else {
        res.json("文件不存在")
      }
    })
  
  
})

export default  router;